# 通用的http Post/Get方法访问远程url（API）获取/推送数据的通用函数
# by lw 2023-11-5

import requests
import json



def http_get(url, params, timeout=30) -> json:
    """使用get方式获取/推送数据

    Args:
        url (_type_): _description_
        params (_type_): _description_
        timeout (int, optional): _description_. Defaults to 30.

    Returns:
        json: _description_
    """
    try:
        headers = {
            "Content-Type":
            "application/json",
            'User-Agent':
            'Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
        }
        response = requests.get(url,
                                params=params,
                                headers=headers,
                                timeout=timeout)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(url, '获取数据失败！', e.args)
        return None


def http_post(url: str, json: json, data=None, timeout=30) -> json:
    """使用post方式访问远程url获取/推送数据

    Args:
        url (str): 	请求的 url
        json (json): 要发送到指定 url 的 JSON 对象
        data (_type_, optional): 要发送到指定url的字典、元组列表、字节或文件对象,默认值：None.
        timeout (int, optional): 指示等待客户端建立连接和/或发送响应的时间，默认值：30s.

    Returns:
        json: 使用json格式存放的数据
    """
    try:
        headers = {
            "Content-Type":
            "application/json",
            'User-Agent':
            'Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
        }
        response = requests.post(url,
                                 data=data,
                                 json=json,
                                 headers=headers,
                                 timeout=timeout)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(url, '获取数据失败！', e.args)
        return None
